<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.merchant_name" placeholder="商户名称/收款人" style="width: 130px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.province" placeholder="请选择省" filterable class="filter-item" style="width: 130px;" @change="changeRegionProvince">
        <el-option v-for="(province,index) in this.merchant_province" :label="province.name" :value="province.region_id"
          :key="index" />
      </el-select>
      <el-select v-model="listQuery.city" placeholder="请选择市"  style="width: 130px;" filterable class="filter-item" @change="changeRegionCity">
        <el-option v-for="(city,index) in this.merchant_city" :label="city.name" :value="city.region_id" :key="index" />
      </el-select>
      <el-select v-model="listQuery.district" placeholder="请选择区县" filterable style="width: 130px;" class="filter-item">
        <el-option v-for="(district,index) in this.merchant_district" :label="district.name" :value="district.region_id"
          :key="index" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <!-- <el-button v-waves class="filter-item" type="primary" icon="el-icon-search"  @click="excelout">导出</el-button> -->
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" size="mini"  border fit highlight-current-row style="width: 100%;">
      <!-- <el-table-column label="ID" prop="id" align="center">
        <template slot-scope="{row}">
          <span>{{ row.merchant_id }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="省" align="center" >
        <template slot-scope="{row}">
          <span>{{ row.province_name }}</span>
        </template>
      </el-table-column>
       <!-- <el-table-column label="签约日期" align="center" width="160px">
        <template slot-scope="{row}">
          {{ row.create_time }}
        </template>
      </el-table-column> -->
      <el-table-column label="地址" align="center" >
        <template slot-scope="{row}">
          <span>{{ row.city_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商户名称" align="center" >
        <template slot-scope="{row}">
          <span>{{ row.merchant_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="海尔云贷商户id" align="center"  >
        <template slot-scope="{row}">
          <span>{{ row.haier_merchantid }}</span>
        </template>
      </el-table-column>

      <el-table-column label="医美类型" align="center" >
        <template slot-scope="{row}">
          <span>{{ row.merchant_type == 1?'医美':'生美' }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="海尔云贷" align="center"  width="80px">
        <template slot-scope="{row}">
          <span>{{ row.haier_online == 1?'已上线':'未上线' }}</span>
        </template>
      </el-table-column> -->

      <!-- <el-table-column label="打款比例" align="center"  width="150px">
        <template slot-scope="{row}">
          <span>{{ row.pay_rate }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="收款账号" align="center"  width="170px">
        <template slot-scope="{row}">
          <span>{{ row.bank_number }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收款人" align="center"  width="260px">
        <template slot-scope="{row}">
          <span>{{ row.pay_person }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开户行地址" align="center" width="280px">
        <template slot-scope="{row}">
          <span>{{ row.bank_address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="证件号" align="center" width="180px">
        <template slot-scope="{row}">
          <span>{{ row.idnumber }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="签章授权" align="center" width="80px">
        <template slot-scope="{row}">
          <el-switch v-model="row.merchant_auth" @change="change_auth(row)" active-color="#13ce66"></el-switch>
        </template>
      </el-table-column> -->

 
      <!-- <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog title="新增云贷商户" :visible.sync="dialogFormVisible" width="660px" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 60%; margin-left:70px;">
        <el-tabs v-model="activeName">
          <el-tab-pane label="工商信息" name="first">
            <el-form-item label="商户名称" prop="merchant_name">
              <el-input v-model="temp.merchant_name" type="text" placeholder="请输入企业名称" style="width: 200px;"/>
            </el-form-item>
            <el-form-item label="商户id" prop="haier_merchantid">
              <el-input v-model="temp.haier_merchantid" type="text" placeholder="请输入商户id" style="width: 200px;"/>
            </el-form-item>
            <el-form-item label="商户简称" prop="sort_name">
              <el-input v-model="temp.sort_name" type="text" placeholder="请输入企业简称" style="width: 200px;"/>
            </el-form-item>
          
            <el-form-item label="医美类型" prop="merchant_type">
              <el-select v-model="temp.merchant_type" placeholder="请选择医美类型">
                <el-option label="医美" :value="1" />
                <el-option label="生美" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="所在省份" prop="province">
              <el-select v-model="temp.province" placeholder="请选择省份" filterable @change="changeRegionProvince">
                <el-option v-for="(province,index) in this.merchant_province" :label="province.name" :value="province.region_id"
                  :key="index" />

              </el-select>
            </el-form-item>
            <el-form-item label="所在城市" prop="city">
              <el-select v-model="temp.city" placeholder="请选择市" filterable @change="changeRegionCity">
                <el-option v-for="(city,index) in this.merchant_city" :label="city.name" :value="city.region_id" :key="index" />

              </el-select>
            </el-form-item>
            <el-form-item label="所在区县" prop="district">
              <el-select v-model="temp.district" placeholder="请选择区县">
                <el-option v-for="(district,index) in this.merchant_district" filterable :label="district.name" :value="district.region_id"
                  :key="index" />
              </el-select>
            </el-form-item>
           
           
          </el-tab-pane>
        </el-tabs>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogCheckVisible" title="Reading statistics">
      <el-form ref="dataCheckForm" :rules="rule" :model="tempCheck" label-position="left" label-width="100px" style="width: 80%; margin-left:70px;">
        <el-form-item label="请选择等级" prop="level_id">
          <el-select v-model="tempCheck.level_id" placeholder="请选择等级">
            <el-option v-for="(level,index) in this.level_list" :label="level.name" :value="level.id" :key="index" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogCheckVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleChecked">确认</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" width="900px">
      <img :src="dialogImageUrl" alt="" width="800px">
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchMerchantBase,
    fetchMerchantRegion,
    fetchList,
    createHaierMerchant,
   
    updateMerchantChecked,
    updateMerchant,
    deleteMerchant,
    exceloutmerchant
  } from '@/api/merchant'
  import excel from '@/components/excelout/index.vue'
  import waves from '@/directive/waves' // waves directive
  import {
    parseTime,getNodes
  } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  export default {
    name: 'ComplexTable',
    components: {
      Pagination,excel
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          0: 'danger'
        }
        return statusMap[status]
      },
      statusNameFilter(status) {
        const statusNameMap = {
          1: '启用',
          0: '禁用'
        }
        return statusNameMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        action: process.env.VUE_APP_BASE_API + '/backend_upload',
        myHeaders: {
          token: this.$store.getters.token
        },
        accountNode:false,
        activeName: 'first',
        imageUrl: '',
        tableKey: 0,
        nodes:[],
        value:true,
        limit: 1,
        list: null,
        value1:'2020-10-15',
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          merchant_name: '',
          merchant_id: '',
          province: '',
          city: '',
          district: '',
          investor_id:2,

        },
        fileList: [],
        heTongFileList: [],
        businessFileList: [],
        bankPermitfileList: [],
        businessLicensefileList: [],
        medicalfileList: [],
        AuthfileList: [],
        idCardFanfileList: [],
        idCardZhengfileList: [],
        sortOptions: [{
          label: 'ID Ascending',
          key: 'sale_id asc'
        }, {
          label: 'ID Descending',
          key: 'sale_id desc'
        }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        // is_alone:"1",
        tempCheck: {
          level_id: '',
          is_checked: 1,
          merchant_id: ''
        },
        temp: {
          merchant_name: '',
          haier_merchantid:'',
          sort_name:'',
          province: '',
          city: '',
          district: '',
          merchant_type:1
        },
        data: {
          third_platform: []
        },
        dialogCheckVisible: false,
        dialogFormVisible: false,
        dialogImageUrl: '',
        dialogVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        idCard_zheng: '',
        idCard_fan: '',
        medical_license: '',
        business_license: '',
        bank_permit: '',
        business_information: '',
        level_list: [],
        merchant_type: [],
        merchant_level: [],
        merchant_province: [],
        merchant_city: [],
        merchant_district: [],
        merchant_service: [],
        dialogPvVisible: false,
        pvData: [],
        rule: {
          level_id: [{
            required: true,
            message: '等级必须选择',
            trigger: 'change'
          }]
        },
        rules: {
          merchant_name: [{
            required: true,
            message: '商户名称必须填写',
            trigger: 'change'
          }],
          haier_merchantid: [{
            required: true,
            message: '海尔商户id必填',
            trigger: 'change'
          }],
       
          merchant_type: [{
            required: true,
            message: '商户类型必须选择',
            trigger: 'change'
          }],
          province: [{
            required: true,
            message: '省份必须选择',
            trigger: 'change'
          }],
          city: [{
            required: true,
            message: '城市必须选择',
            trigger: 'change'
          }],
          district: [{
            required: true,
            message: '区县必须选择',
            trigger: 'change'
          }],
          sort_name: [{
            required: true,
            message: '商户简称必填',
            trigger: 'change'
          }],
        },
        downloadLoading: false
      }
    },
    created() {
      
      this.listQuery.merchant_id = this.$route.params.merchant_id
      this.cacheQueryFormat();
      this.getList();
      this.nodes = getNodes();
      //添加钩子，页面刷新
      window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
    destroyed() {
      //添加钩子，页面刷新
      window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
    methods: {
      excelout() {
      this.listLoading = true
      this.listQuery.page = 1
      this.listQuery.limit = this.total
      exceloutmerchant(this.listQuery).then(response => {
        this.listLoading = false
        const filepath = response.data.path
        window.location.href = filepath
      })
    },
      beforeunloadFn(e) {
        //刷新页面事件
        sessionStorage.removeItem('merchantHaierList');
      },
      cacheQueryFormat(){
        let cacheQuery = sessionStorage.getItem('merchantHaierList');
        if(cacheQuery){
          this.listQuery = JSON.parse(cacheQuery);
        }
      },
      handlePreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },

      getList() {
        sessionStorage.setItem('merchantHaierList',JSON.stringify(this.listQuery))
        fetchMerchantBase().then(res => {
          this.merchant_type = res.data.type
          this.merchant_level = res.data.merchant_level
          this.merchant_province = res.data.province
          this.level_list = res.data.level_list
        })
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          this.list = response.data.data
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 1.0 * 1000)
        })
      },
      handleCheck(row) {
        this.dialogCheckVisible = true
        this.tempCheck.merchant_id = row.merchant_id
      },
      handleChecked() {
        this.$refs['dataCheckForm'].validate((valid) => {
          if (valid) {
            updateMerchantChecked(this.tempCheck).then(() => {
              this.dialogCheckVisible = false
              this.$refs['dataForm'].resetFields();
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000,
                onClose: this.getList()
              })
            })

          }
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
     
      handleCreate() {
        this.accountNode = true;
        fetchMerchantBase().then(res => {
          this.merchant_type = res.data.type
          this.merchant_level = res.data.level
          this.merchant_province = res.data.province
        })
        this.dialogStatus = 'create'
        this.dialogFormVisible = true

        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          this.$refs['dataForm'].resetFields();
        })

      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            createHaierMerchant(this.temp).then((res) => {
                this.dialogFormVisible = false
                if(res.code==200){
                  this.$notify({
                    title: '新增成功',
                    message: '成功！',
                    type: 'success',
                    duration: 2000,
                    onClose: this.getList()
                  })
                }else{
                  this.$notify({
                    title: '失败',
                    message: '失败！',
                    type: 'error',
                    duration: 2000,
                    onClose: this.getList()
                  })
                }
               
              })
            }
        })
      },
      handleUpdate(row) {
        this.accountNode = false;
        if(this.nodes.indexOf('139')!=-1){
          this.accountNode = true;
        }
        this.data.idCard_zheng = row.idCard_zheng
        this.data.idCard_fan = row.idCard_fan
        this.data.medical_license = row.medical_license_pic
        this.data.business_license = row.business_license_pic
        this.data.bank_permit = row.bank_permit_pic

        this.temp.third_platform = row.third_platform
        this.temp.merchant_type = row.merchant_type
        this.fileList = row.third_platform_pic

        this.temp.hetong = row.hetong
        this.heTongFileList = row.hetong_pic

        this.temp.business = row.hetong
        this.businessFileList = row.business_pic

        this.temp.bank_permit.push(row.bank_permit);
        this.bankPermitfileList = row.bank_permit_pic

        this.temp.business_license = row.business_license
        this.businessLicensefileList = row.business_license_pic

        this.temp.medical_license.push(row.medical_license);
        this.medicalfileList = row.medical_license_pic

        this.temp.merchant_auth_file.push(row.merchant_auth_file);
        this.AuthfileList = row.auth_license_pic

        this.temp.law_person_idcard_fan = row.law_person_idcard_fan
        this.idCardFanfileList = row.idCard_fan

        this.temp.law_person_idcard_zheng = row.law_person_idcard_zheng
        this.idCardZhengfileList = row.idCard_zheng


        this.temp = Object.assign({}, row) // copy obj
        fetchMerchantBase().then(res => {
          this.merchant_type = res.data.type
          this.merchant_level = res.data.level
          this.merchant_province = res.data.province
        })
        this.changeRegionProvince(this.temp.province)
        this.changeRegionCity(this.temp.city)
        this.temp.password = ''
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if ((this.temp.hetong.length > 0) && (this.temp.business.length > 0)) {
              updateMerchant(tempData).then(() => {
                const index = this.list.findIndex(v => v.id === this.temp.id)
                this.list.splice(index, 1, this.temp)
                this.dialogFormVisible = false
                this.$refs['dataForm'].resetFields();
                this.$notify({
                  title: 'Success',
                  message: 'Update Successfully',
                  type: 'success',
                  duration: 2000,
                  onClose: this.getList()
                })
              })
            } else {
              this.$notify({
                title: 'error',
                message: '资料不完整',
                type: 'error',
                duration: 2000
              })
            }
          }

        })
      },
      handleDelete(row, index) {

        deleteMerchant(row.merchant_id).then(response => {
          this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      changeRegionProvince(val) {
        let pam = {pid:val};
        fetchMerchantRegion(pam).then(res => {

          this.merchant_city = res.data
        })
      },
      changeRegionCity(val) {
        let pam = {pid:val};
        fetchMerchantRegion(pam).then(res => {

          this.merchant_district = res.data
        })
      },
      UploadUrl: function() {
        return this.action
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    white-space: nowrap;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    float: left;
  }
</style>
